/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package in.co.sneh.controller;

import in.co.sneh.model.FileUpload;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

/**
 *
 * @author CEBALLOS
 */
public class FileUploadServer extends HttpServlet {
    
    
    private int i=-1;
    public ArrayList<String> datos = new ArrayList<String>();           
             
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            
           ServletFileUpload upload = new ServletFileUpload();
           
            try {
                FileItemIterator itr = upload.getItemIterator(request);
                
                 while (itr.hasNext()) {
                    
                    FileItemStream item = itr.next();
                    //String name = item.getFieldName();
                    
                    //String fileName = item.getName();
                    
                    if (item.isFormField()) {
                        InputStream stream = item.openStream();
                       
                         //do field specific procces
                        String fieldName = item.getFieldName();
                        //do file upload specific procces
                        InputStream Archivo = item.openStream();
                         i=i+1;
                        System.out.println("---------"+i);
                                                             
                        //System.out.println(Streams.asString(stream) + "-------");
                                     
                       
                        byte[] b = new byte[Archivo.available()];
                        Archivo.read(b);


                        String value = new String(b);
                        System.out.println(b+"----------------------------------------");
                        System.out.println(fieldName + ":" + value + "");
                        datos.add(i,value);
                        System.out.println(datos);
                        response.getWriter().println(fieldName + ":" + value + "<br/>");

                        
                    } else {
                                                
                       String cedula= datos.get(0);
                       String nombres = datos.get(1);

                        String ruta = getServletContext().getRealPath("");

                        //call method to upload file

                             if (FileUpload.ProcesarArchivo(ruta, item)) {
                             FileUpload FL =new FileUpload();                        
                             FL.ProcesarArchivosql(ruta, item,Integer.parseInt(cedula),nombres);
                             datos.clear();
                             i=-1;
                                     
                                    
                                       
 
                            response.getWriter().println("archivo subido correctamente");
                        } else {
                            response.getWriter().println("archivo no subido");
                        }


                    }

                }
              } finally {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
